//
//  ViewController.m
//  LANDSKY
//
//  Created by 3TI on 14-2-10.
//  Copyright (c) 2014年 qiaquan. All rights reserved.
//

#import "LoginViewController.h"

#import "RegisterViewController.h"

#import "TaskWithLogin.h"
#import "LoginObject.h"

@interface LoginViewController ()<WYHttpTaskDelegate,RegisterViewControllerDelegate>

@property(nonatomic,strong)LoginObject* login;

@property (nonatomic,strong)MBProgressHUD *mb;
@end

@implementation LoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    
    self.username.layer.borderColor = [[UIColor darkGrayColor] colorWithAlphaComponent:.4].CGColor;
    self.username.layer.borderWidth = 1.0f;
    self.password.layer.borderColor = [[UIColor darkGrayColor] colorWithAlphaComponent:.4].CGColor;
    self.password.layer.borderWidth = 1.0f;
    [self.backBtn addTarget:self action:@selector(on_btn_back:) forControlEvents:UIControlEventTouchUpInside];

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.username resignFirstResponder];
    [self.password resignFirstResponder];
}
/*
 具体步骤如下：
 1，用 POST 方式发送请求：
 http://itunes.apple.com/search?term=你的应用程序名称&entity=software
 
 更加精准的做法是根据 app 的 id 来查找：
 http://itunes.apple.com/lookup?id=你的应用程序的ID
 #define APP_URL http://itunes.apple.com/lookup?id=你的应用程序的ID
 
 你的应用程序的ID 是 itunes connect里的 Apple ID
 
 2，从获得的 response 数据中解析需要的数据。因为从 appstore 查询得到的信息是 JSON 格式的，所以需要经过解析。解析之后得到的原始数据就是如下这个样子的：
 {
 resultCount = 1;
 results =     (
 {
 artistId = 开发者 ID;
 artistName = 开发者名称;
 price = 0;
 isGameCenterEnabled = 0;
 kind = software;
 languageCodesISO2A =             (
 EN
 );
 trackCensoredName = 审查名称;
 trackContentRating = 评级;
 trackId = 应用程序 ID;
 trackName = 应用程序名称";
 trackViewUrl = 应用程序介绍网址;
 userRatingCount = 用户评级;
 userRatingCountForCurrentVersion = 1;
 version = 版本号;
 wrapperType = software;
 }
 );
 }
 
 然后从中取得 results 数组即可，具体代码如下所示：
 
 NSDictionary *jsonData = [dataPayload JSONValue];
 NSArray *infoArray = [jsonData objectForKey:@"results"];
 NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
 NSString *latestVersion = [releaseInfo objectForKey:@"version"];
 NSString *trackViewUrl = [releaseInfo objectForKey:@"trackViewUrl"];
 
 如果你拷贝 trackViewUrl 的实际地址，然后在浏览器中打开，就会打开你的应用程序在 appstore 中的介绍页面。当然我们也可以在代码中调用 safari 来打开它。
 UIApplication *application = [UIApplication sharedApplication];
 [application openURL:[NSURL URLWithString:trackViewUrl]];
 
 
 
 
 [cpp] view plaincopyprint?
 -(void)onCheckVersion:(NSString *)currentVersion
 {
 NSString *URL = APP_URL;
 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
 [request setURL:[NSURL URLWithString:URL]];
 [request setHTTPMethod:@"POST"];
 NSHTTPURLResponse *urlResponse = nil;
 NSError *error = nil;
 NSData *recervedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
 
 NSString *results = [[NSString alloc] initWithBytes:[recervedData bytes] length:[recervedData length] encoding:NSUTF8StringEncoding];
 NSDictionary *dic = [results JSONValue];
 NSArray *infoArray = [dic objectForKey:@"results"];
 if ([infoArray count]) {
 NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
 NSString *lastVersion = [releaseInfo objectForKey:@"version"];
 
 if (![lastVersion isEqualToString:currentVersion]) {
 trackViewURL = [releaseInfo objectForKey:@"trackVireUrl"];
 UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"更新" message:@"有新的版本更新，是否前往更新？" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil] autorelease];
 [alert show];
 }
 }
 }

 */
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"register"]){
        RegisterViewController *s = segue.destinationViewController;
        s.delegate = self;
    }
}

-(void)registerDidSuccess{
    
}


#pragma mark - http delegate -

-(void)requestCompleteWithObj:(WYHttpTask *)obj{
    
    id rsult = [obj parese];
    
    if([obj isKindOfClass:[TaskWithLogin class]]){
        
        self.login = rsult;
//        [Utils saveToLocalPlistForValue:self.login.nickname key:@"nickname"];
//        [Utils saveToLocalPlistForValue:self.login.grade key:@"grade"];
//        [Utils saveToLocalPlistForValue:self.login.logindays key:@"logindays"];
//        [Utils saveToLocalPlistForValue:self.login.icon key:@"icon"];
        
        [self on_btn_back:nil];
    }
    
}
-(void)requestFailWithMsg:(WYHttpTask *)obj{
    DLog(@"%@",obj.networkOp.url);

    self.mb.labelText = obj.rcvData;
    [self.mb hide:YES afterDelay:.8];
}


-(void)on_btn_back:(UIButton *)btn{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)on_btn_login:(id)sender {
    
    if(!self.username.text.length){
        [UIAlertView showAlertViewWithTitle:@"用户名不能为空"];
        return;
    }
    
    if(!self.password.text.length){
        [UIAlertView showAlertViewWithTitle:@"密码不能为空"];
        return;
    }
    
    
    MBProgressHUD *mb = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.mb = mb;
    
    TaskWithLogin *login = [[TaskWithLogin alloc] initWithName:self.username.text withPwd:self.password.text];
    login.delegate = self;
    [login start];
    
}
@end
